<template>
    <div id="vbox" style="margin: 0 auto;" :style="{ 'width': width + 'px', 'height': height + 'px' }">
        <video id="videoPlayer" :options="videoOptions" class="video-js"></video>
    </div>
    <div v-if="leftTime > -1"
        style="color:#DDD;position: relative;margin: -460px auto;width: 100px;text-align: center;font-size: 80px;background-color: #333;border-radius: 50%;">
        {{ leftTime }}</div>
    <div v-if="playNext > -1" style="color:#DDD;position: relative;margin: -460px auto;width: 400px;text-align: center;font-size: 80px;background-color: #333;border-radius: 50px;">
        {{ playNext }}
        <div>
            <VideoPause @click="playNext = -2" style="width: 1em; height: 1em;" />
            <VideoPlay @click="playNext = 0" style="width: 1em; height: 1em;margin-left: 80px" />
        </div>
    </div>    
</template>

<script setup>
import videojs from 'video.js';
import { ref, onMounted } from 'vue';
import { VideoPause, VideoPlay } from '@element-plus/icons-vue';

const leftTime = ref(5);
const playNext = ref(-1);
const adToken = ref('');
const videoOptions = ref({
    autoplay: true,
    controls: true,
    liveui: true,
    responsive: true,
    playbackRates: [0.75, 1, 1.25, 1.5, 1.75, 2],
    width: 1280,
    height: 720,
    sources: [{
        src: 'data:application/x-mpegURL;base64,',
        type: 'application/x-mpegURL'
    }]
});
const width = ref(1280);
const height = ref(720);
const videoPath = ref("");
videoPath.value = decodeURI(location.search.substring(1));

onMounted(()=>{
    loadVideo();
    window.addEventListener("beforeunload", (event) => {
        if (player) {
            localStorage.setItem(videoPath.value, player.currentTime());
        }
    });
    resize();
    window.onresize = resize;    
})

//加载视频
async function loadVideo(){
    let m3u8Pre = await BaiduPan("video", videoPath.value);
    //console.log(m3u8Pre, Date.now());
    if (m3u8Pre.errno == 133) { //遇到133错误码，需先等待广告播放时间后，才可请求到视频流
        leftTime.value = m3u8Pre.ltime;
        adToken.value = m3u8Pre.adToken;
        setTimeout(refresh, 1000);
    }

    //标题中显示文件名
    let fList = JSON.parse(localStorage.getItem("play_path"));
    for(let f of fList){
        if(f.path == videoPath.value){
            let titles = document.title.split("|");
            if(titles.length > 1){
                titles[0] = f.server_filename;
            }else{
                titles.unshift(f.server_filename);
            }
            document.title = titles.join(" | ");
            //console.log(titles);
            break;
        }
    }
}

function resize() {
    width.value = window.innerWidth;
    height.value = window.innerHeight - 1;
    setTimeout(() => {
        height.value = window.innerHeight;
    }, 100);
}

/** 刷新视频 */
let player = null;
async function refresh() {
    leftTime.value--;
    if (leftTime.value < 0) {
        let m3u8 = await BaiduPan("video", videoPath.value, adToken.value); //真正的视频文件
        videoOptions.value.sources[0].src = 'data:application/x-mpegURL;base64,' + m3u8;
        let vplayer = document.querySelector("#videoPlayer");
        if(vplayer == null){
            document.querySelector("#vbox").innerHTML = '<video id="videoPlayer" class="video-js"></video>';
            vplayer = document.querySelector("#videoPlayer");
        }
        let player0 = videojs(vplayer, videoOptions.value, () => { });

        if (player == null) {
            player = player0;
            const MenuButton = videojs.getComponent('MenuButton');
            const Menu = videojs.getComponent('Menu');
            const MenuItem = videojs.getComponent('MenuItem');
            const myMenu = new Menu(player)
            let myMenuItem = new MenuItem(player, { label: "刷新" })
            myMenuItem.on('click', $event => {
                refresh()
            })
            myMenu.addItem(myMenuItem);
            myMenuItem = new MenuItem(player, { label: "关闭" })
            myMenuItem.on('click', $event => {
                window.close();
            })
            myMenu.addItem(myMenuItem);

            const myMenuButton = new MenuButton(player)
            myMenuButton.addChild(myMenu)
            //myMenuButton.controlText('gg')
            myMenuButton.addClass('hong-menu-button')
            player.controlBar.addChild(myMenuButton, {});
            //开始播放判断是否播放过，播放过跳转到上次的时间
            player.ready(() => {
                let lastPlayTime = localStorage.getItem(videoPath.value);
                if (lastPlayTime) {
                    player.currentTime(lastPlayTime);
                }
            });
            //检查是否有下个视频，有播放自动播放下个视频
            player.on("ended", ()=>{
                //console.log("ended", videoPath.value);
                //标题中显示文件名
                let fList = JSON.parse(localStorage.getItem("play_path"));
                //console.log(fList);
                let fd = false;
                for(let f of fList){
                    if(fd){
                        //找到视频音频准备播放下一个
                        if(f.category == 1 || f.category == 2){
                            //console.log(f);
                            videoPath.value = f.path;
                            playNext.value = 5;
                            videoNext();
                            break;
                        }
                    }else{
                        if(f.path == videoPath.value){
                            fd = true;
                        }
                    }
                }
                //player.dispose();
            });
        }
        //console.log(m3u8, Date.now());
        // let player = videojs(videoPlayer.value, {autoplay: true, controls: true,playbackRates: [0.5, 0.75, 1, 1.5, 1.75, 2],sources: [{src:'data:application/x-mpegURL;base64,' + m3u8,type: 'application/x-mpegURL'}]}, () => {
        //   //this.player.log('onPlayerReady');
        // }); 
        // player.on("contextmenu", function(e){
        //   e.preventDefault();
        // });         
    } else {
        setTimeout(refresh, 1000);
    }
}
//下个视频倒计时
function videoNext(){
    playNext.value--;
    if(playNext.value < 0){
        if(playNext.value == -1){
            player.dispose();
            player = null;
            loadVideo();
        }
    }else{
        setTimeout(videoNext, 1000);
    }
}
</script>

<style>
body {
    padding: 0;
    margin: 0;
}

.video-js {
    width: 100%;
    height: 100%;
}

.hong-menu-button .vjs-menu {
    width: 6em;
}

.hong-menu-button .vjs-icon-placeholder:before {
    font-family: VideoJS;
    content: "\f114";
}
</style>